import csv
from flask import Flask, Response, Blueprint
from io import StringIO
from models import db, House  # Assuming this imports your SQLAlchemy models
from settings import Config
app = Flask(__name__)
app.config.from_object(Config)
db.init_app(app)

chuli = Blueprint('chuli', __name__)
# Route to generate and download UTF-8 encoded CSV file
@chuli.route('/chuli')
def download_houses_csv():
    # Query all House records from your database
    Houses = House.query.all()

    # Create an in-memory file-like object
    output = StringIO()

    # Use csv.writer to write to the in-memory file-like object
    csv_writer = csv.writer(output)
    csv_writer.writerow(['id', '区域', '小区名称', '户型', '面积', '价格', '位置'])

    for house in Houses:
        # Replace '-' with ' ' in the address field
        corrected_address = house.address.replace('-', '')

        # Write row to CSV
        csv_writer.writerow([
            house.id,
            house.region,
            house.block,
            house.rooms,
            house.area,
            house.price,
            corrected_address  # Use the corrected address here
        ])

    # Set up the response to serve the CSV file with UTF-8 encoding
    response = Response(output.getvalue(), mimetype='text/csv; charset=utf-8')
    response.headers['Content-Disposition'] = 'attachment; filename=Houses.csv'

    return response


if __name__ == '__main__':
    app.run(debug=True)
